/**
 * @function useRenders
 * @Author: linzy
 * @Date: 2022-05-09
 * 传参：columns传入的参数一致 新增几个新的参数 render, type, tdWidth, 传入不同的类型能实现不同的功能 比如权重编辑 图片预览 金额换算等
 *    @param {string} type -
 *      index： 下标 结合后台返回的limit、page生成 <br />
 *      money 金额显示，做了/100处理，同时会每三位隔断 <br />
 *      date 日期 <br />
 *      dateMinute 日期 精确到分钟 <br />
 *      datetime 日期 精确到秒 <br />
 *      preview 预览 <br />
 *      copy 复制 <br />
 *      status 状态 需要传入enum 枚举如{1:'下线',2:'上线'} 也可以传入options 如
 *        [
            { label: "待核销", value: 0, type: 'info', },
            { label: "已核销", value: 1, type: 'success', },
          ]
          其中的type是Tag组件的样式 详情查看tagColorObj
          <br />
 *      weight 状态 传入 onChange(params) params = {id,weight} <br />
 *      tag 状态 支持数组，字符串需要传入separator 默认为‘ ’空格 <br />
 *      range 日期范围 需要传入dataIndex的格式为 'startTime,endTime' <br />
 *      images 多图片显示 需要传入attrName 属性名，如：attrName: 'mediaUrl' <br />
 *    @param {string} render - 传入render则表示 自行实现 用于拓展
 *    @param {boolean | function} show - 是否显示该项
 *    @param {string} tdWidth - 限制表格的宽度即表格字数
 */
import { Typography, Tag, Tooltip } from "antd";
import DJStatistic from "@/components/DJStatistic";
import { DJStarEdit } from "@/components";
import { useConstants } from "@/hooks";
import { typeOf } from "@/hooks/tools";
import _ from "lodash";
import { addImgSuffix } from "@/utils/utils";
import { getDateFormat } from "@/hooks/tools";
import { WeightPopover } from "@/hooks/components";
import * as gConfig from "@/config";
import { getFloatNum } from "@/hooks/tools";
const tagColorObj = {
  info: "blue",
  success: "green",
  warning: "orange",
  error: "red",
  default: ""
};
const mpJumpObj = _.keyBy(gConfig.mpJumpOptions, "value");

export default () => {
  const { FILE_SERVER, ENV_TAG } = useConstants();
  const renders = {
    index: tableForm => {
      const { page, limit } = tableForm;
      return function render(text, record, index) {
        if (page && limit) {
          return (page - 1) * limit + index + 1;
        } else {
          return index + 1;
        }
      };
    },
    money: function (item) {
      return function render(text, record, index) {
        return <DJStatistic value={text} {...item.props} />;
      };
    },
    percent: text => (_.isNil(text) ? null : getFloatNum(text, "*", 100) + "%"),
    date: text => {
      return text ? getDateFormat(text, "date") : null;
    },
    dateMinute: text => {
      return text ? getDateFormat(text, "dateMinute") : null;
    },
    datetime: text => {
      return text ? getDateFormat(text, "datetime") : null;
    },
    preview: item => {
      return function render(text) {
        return (
          text && (
            <a
              href={FILE_SERVER + text}
              target="_blank"
              rel="noopener noreferrer"
            >
              <img
                alt=""
                style={{
                  objectFit: "contain",
                  width: "68px",
                  height: "68px",
                  ...item?.imgStyle
                }}
                src={addImgSuffix(url, item.ossImageSize || 68)}
              />
            </a>
          )
        );
      };
    },
    avatar: (item) => {
      return function render(text) {
        var url = _.isObject(text) ? text[item.key || "url"] : text;
        return text ? (
          <a href={FILE_SERVER + url} target="_blank" rel="noopener noreferrer">
            <Avatar
              size={item.size || 68}
              icon="user"
              src={addImgSuffix(url, item.size || 68)}
              alt=""
            />
          </a>
        ) : (
          <Avatar size={item.size || 68} icon="user" alt="" />
        );
      };
    },
    pics: item => {
      const { width = 68, ossWidth } = item;
      return function render(text) {
        if (!text) return null;
        let picArr = [];
        if (typeOf(text) === "array") {
          picArr = text;
        } else if (typeof text === "string" && /\[/.test(text)) {
          picArr = JSON.parse(text);
        } else {
          picArr = [text];
        }
        return picArr.map(pic => {
          var url = item.attrName ? pic[item.attrName] : pic;
          return url ? (
            <a
              href={FILE_SERVER + url}
              target="_blank"
              rel="noopener noreferrer"
            >
              <img
                alt=""
                width={width}
                height={width}
                style={{
                  objectFit: "cover",
                  margin: "0 5px 5px 0",
                  ...item?.imgStyle
                }}
                src={addImgSuffix(
                  url,
                  ossWidth !== undefined ? ossWidth : width
                )}
              />
            </a>
          ) : null;
        });
      };
    },
    copy: text =>
      text ? (
        <Typography.Paragraph style={{ marginBottom: 0 }} copyable>
          {text}
        </Typography.Paragraph>
      ) : null,
    status: item => {
      let { enum: obj, options } = item;
      if (options?.length) {
        obj = options.reduce((t, v) => {
          if (v.type) {
            return { ...t, [v.value]: { type: v.type, label: v.label } };
          } else {
            return { ...t, [v.value]: v.label };
          }
        }, {});
      }
      return text => {
        return obj?.[text] !== undefined ? (
          _.isObject(obj[text]) ? (
            <Tag color={tagColorObj[obj[text].type]}>{obj[text].label}</Tag>
          ) : (
            obj[text]
          )
        ) : obj?.["default"] !== undefined ? (
          obj["default"]
        ) : null;
      };
    },
    weight: function (item) {
      const {
        onChange,
        key = "id",
        loading,
        title,
        max,
        precision,
        showWeight
      } = item;
      return function render(text, record, index) {
        return (showWeight && showWeight(record)) ||
          showWeight === undefined ? (
          <WeightPopover
            title={"修改" + title}
            value={text}
            loading={loading}
            max={max}
            precision={precision}
            onChange={weight => {
              let params = {
                id: record[key],
                weight
              };
              onChange && onChange(params, record, index);
            }}
          />
        ) : (
          text
        );
      };
    },
    star: function (onChange, key = "id") {
      return function render(text, record, index) {
        return (
          <DJStarEdit
            title="修改评分"
            value={text}
            onChange={star => {
              let params = {
                id: record[key],
                star
              };
              onChange && onChange(params, record, index);
            }}
          />
        );
      };
    },
    tag: function (rest) {
      let { separator = " ", key = "name" } = rest;
      return function render(text) {
        let arr = [];
        if (typeOf(text) === "array" && text.length > 0) {
          arr = text;
        } else if (typeOf(text) === "string" && text.length > 0) {
          arr = text.trim().split(separator);
        } else {
          return rest.default ? rest.default : null;
        }
        return arr.map(item => {
          return <Tag>{_.isObject(item) ? item[key] : item}</Tag>;
        });
      };
    },
    range: function (dataIndex, mode = "dateTime") {
      var arr = dataIndex.split(",");
      return function render(text, record) {
        var rangeArr = [];
        rangeArr[0] = getDateFormat(record[arr[0]], mode);
        rangeArr[1] = getDateFormat(record[arr[1]], mode);
        return _.chain(rangeArr).compact().join(" ~ ").value();
      };
    },
    djType: function (djTypeList) {
      return function render(text) {
        const row = djTypeList.find(item => item.typeid === text);
        return row && row.typename;
      };
    },
    mpType: function render(text) {
      return mpJumpObj[text]?.label;
    },
    mpUrl: function (item) {
      const { mpType = "appletAddrType" } = item;
      return function render(text, record) {
        if (text) {
          text = decodeURIComponent(text);
          const appletAddrType = record[mpType];
          const mpJumpItem = mpJumpObj[appletAddrType];
          return mpJumpItem ? text.replace(mpJumpItem.prefix, "") : text;
        } else {
          return text;
        }
      };
    },
    link: function (onClick) {
      return function render(text, record) {
        return <a onClick={() => onClick(text, record)}>{text}</a>;
      };
    },
    ellipsis: function (text) {
      return (
        <Tooltip title={text}>
          <div className="two_row_ellipsis">{text}</div>
        </Tooltip>
      );
    },
    decode: function (text) {
      return text ? (
        <Tooltip title={text}>
          <Typography.Paragraph style={{ marginBottom: 0 }} copyable>
            <div className="two_row_ellipsis">{decodeURIComponent(text)}</div>
          </Typography.Paragraph>
        </Tooltip>
      ) : null;
    },
    shortUrl: function (text) {
      return text ? (
        <Typography.Paragraph style={{ marginBottom: 0 }} copyable>
          {`https://${
            ENV_TAG === "test"
              ? "a-t.idj.ink"
              : ENV_TAG === "regress"
              ? "a-r.idj.ink"
              : "a.idj.ink"
          }/${text}`}
        </Typography.Paragraph>
      ) : null;
    },
    shortMpUrl: function (text) {
      return text ? (
        <Typography.Paragraph style={{ marginBottom: 0 }} copyable>
          {`https://${
            ENV_TAG === "test"
              ? "m-t.idj.ink"
              : ENV_TAG === "regress"
              ? "m-r.idj.ink"
              : "m.idj.ink"
          }/${text}`}
        </Typography.Paragraph>
      ) : null;
    },
    video: function (item) {
      const { width, attrName, posterName } = item;
      return function render(text, record) {
        var url = attrName ? text?.[attrName] : text;
        var poster = posterName ? text?.[posterName || "coverUrl"] : text;
        return url ? (
          <video
            width={width || 300}
            src={url}
            controls={true}
            poster={FILE_SERVER + poster}
          ></video>
        ) : null;
      };
    }
  };
  return renders;
};
